package com.example.service;

import com.example.entity.SearchHistory;
import com.example.mapper.SearchHistoryRepository;
import model.CoOccurrenceMatrixBuilder;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import java.util.*;
import java.util.stream.Collectors;
@Service
public class RecommendationService {
    private CoOccurrenceMatrixBuilder matrixBuilder;
    private SearchHistoryRepository searchHistoryRepository;
    /**
     * 构造函数，注入共现矩阵构建器
     * @param matrixBuilder 提供共现矩阵的构建器实例
     */
    public RecommendationService(CoOccurrenceMatrixBuilder matrixBuilder, SearchHistoryRepository searchHistoryRepository) {
        this.matrixBuilder = matrixBuilder;
        this.searchHistoryRepository = searchHistoryRepository;
    }

    /**
     * 根据给定的搜索词推荐相关词汇
     * @param searchTerm 搜索词，用于查找相关的推荐词汇
     * @param limit 推荐结果的数量限制
     * @return 返回一个列表，包含根据共现频率排序的顶部推荐词汇
     */
//    public List<String> recommend(String searchTerm, int limit) {
//        // 获取与搜索词共现的词汇及其共现次数
//        Map<String, Integer> coOccurrences = matrixBuilder.getCoOccurrences(searchTerm);
//
//        // 将共现词汇按共现次数降序排序，提取词汇，限制结果数量，最后收集为列表返回
//        return coOccurrences.entrySet().stream()
//                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
//                .map(Map.Entry::getKey)
//                .limit(limit)
//                .collect(Collectors.toList());
//    }
    public List<String> recommendBasedOnUserHistory(Long userId) {
        // 从数据库获取该用户的搜索历史
        List<SearchHistory> histories = searchHistoryRepository.findByUserId(userId);
        List<String> searchTerms = histories.stream().map(SearchHistory::getSearchTerm).collect(Collectors.toList());

        // 可能需要重新计算或更新共现矩阵，取决于具体实现
        matrixBuilder.buildMatrix(searchTerms);

        // 假设取最近的一个搜索词来生成推荐
        if (!searchTerms.isEmpty()) {
            String lastSearchTerm = searchTerms.get(searchTerms.size() - 1);
            return matrixBuilder.getRecommendations(lastSearchTerm, 5);
        }

        matrixBuilder.printMatrix();

        return new ArrayList<>();
    }
}


